/**
 * 任务相关中间件
 *
 * Created by snowingsea on 2020/02/24.
 */
const tasks = require('./../../models/tasks');
const PhoenixError = require('./../../models/phoenix-error');

/**
 * 需要当前任务存在
 * @param req
 * @param res
 * @param next
 */
function requireTaskExist(req, res, next) {
  if (!req.params.taskId) {
    next(new PhoenixError('invalid request', 'Missing parameters. "taskId" is required'));
    return;
  }
  tasks.getTask(req.params.taskId)
    .then((res) => {
      if (!res) {
        return Promise.reject(new PhoenixError('not found', 'Not found, task not found'));
      }
      req.$task = res;
      return Promise.resolve();
    })
    .then(() => {
      next();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 要求当前任务的访问权限
 * @param req
 * @param res
 * @param next
 */
function requireTaskAccess(req, res, next) {
  let err;
  if (req.$token.userId.toString() !== req.$task.creatorId.toString()) {
    err = new PhoenixError('not found', 'The task is not yours');
  }
  next(err);
}

/**
 * Export model definition object.
 */
module.exports = {
  requireTaskExist,
  requireTaskAccess,
};
